﻿(function ($) {
    $.widget('hwschool.onlinechatmanager', {
        options:
        {
            updatefrequency: 3000,
            emptyAreaText:'Выберите диалог из списка'
        },
        
        tabCounter: 0,
        realTabCounter:0,

        _syncEmptyAreaDiv: function () {
            if (this.realTabCounter == 0) {
                this.emptyDiv.fadeIn('slow');
            }
            else {
                this.emptyDiv.fadeOut('slow');
            }
        },

        _addTab: function (sessionid) {
            var that = this;
            var tabTitle = $("#tab_title"),
            tabContent = $("#tab_content"),
            tabTemplate = "<li class='filt'><a class='filt'  session='#{session}' href='#{href}'>#{label} </a> <span class='ui-icon ui-icon-close' role='presentation'>Remove Tab</span></li>";

            var label = sessionid.substr(sessionid.length - 4) || "Tab " + this.tabCounter,
            tabs  = this.tabs,
            id = "tabs-" + this.tabCounter,
            li = $(tabTemplate.replace(/#\{href\}/g, "#" + id).replace(/#\{label\}/g, label).replace(/#\{session\}/g, sessionid)),
            tabContentHtml = tabContent.val() || "Tab " + this.tabCounter + " content.";
 
            tabs.find( ".ui-tabs-nav" ).append( li );
            tabs.append( "<div class='filt' id='" + id + "'><div class='widgetholder"+ id +" session"+sessionid+"'></div></div>" );

            var chat = $('div.widgetholder'+id, tabs).onlinechat(
                    {
                        title: 'S#' + sessionid,
                        linkedSessionId: sessionid,
                        author: 'Поддержка',
                        authorAlias: 'Я',
                        staticView: true,
                        adminPanel: true
                    });

            chat.bind('onlinechatdialogclosed', function () {
                var sessionID = arguments[1];
                if (sessionID) {
                    var parentDiv = $('div.session' + sessionid, this.sessionID);
                    if (parentDiv.length > 0) {
                        var panelId = parentDiv.parent().attr('id');
                        $('li[aria-controls=' + panelId + ']', this.element).remove();
                        $('.widgetholder' + panelId, this.tabs).onlinechat('destroy');
                        $("#" + panelId).remove();
                        that.realTabCounter--;
                        that.tabs.tabs("refresh");
                        that._syncEmptyAreaDiv();
                    }
                }
            });

            tabs.tabs('refresh');
            this.tabCounter++;
            this.realTabCounter++;
            this._syncEmptyAreaDiv();
        },
        _selectSessionTab:function(sessionId){
            var tabLink = $('a[session="' + sessionId + '"]', this.element);
            tabLink.trigger('click');
        },

        _showChatPanel: function (sessionid) {
            var currentTab = $('div.session'+sessionid);
            if (currentTab && currentTab.length > 0) {
                this._selectSessionTab(sessionid);
            }
            else {
                this._addTab(sessionid);
                this._selectSessionTab(sessionid);
            }
            //var existingTab = $('.' + sessionid, this.chatPlaceholder);
            //if (existingPanel.length == 0) {
            //    var chatPanel = $('<div class="' + sessionid + '"/>');
            //    chatPanel.appendTo(this.chatPlaceholder);
            //    chatPanel.onlinechat(
            //        {
            //            title: 'Введите ответ',
            //            linkedSessionId: sessionid,
            //            author: 'Поддержка',
            //            authorAlias: 'Я'
            //        });
            //}
            //else {
            //    //('already exists.adding some logi is required');
            //}
        },

        _loadSessionInfo:function(){
            var that = this;
            $.get('/api/OnlineMessenger/ActiveMeetings')
                .done(function (data) {
                    var list = $('<ul class="chatlist"/>');
                    if (data.length == 0) {
                        var listItem = $('<ul class="emptyList">список пуст</ul>');
                        listItem.appendTo(list);
                    }
                    else {
                        $.each(data, function (index, value) {
                            var listItem = $('<li/>');
                            var shortSessionid = value.SessionId.substr(value.SessionId.length - 4);
                            var link = $('<a data-chatid=' + value.SessionId + ' href="#chat' + value.SessionId + '">диалог ' + shortSessionid + '<a/>').appendTo(listItem);
                            listItem.appendTo(list);

                            link.bind('click', function (e, args) {
                                var chatId = $(this).attr('data-chatid');
                                that._showChatPanel(chatId);
                            });
                        });
                    }
                    $('ul', that.sessionsListElement).remove();
                    list.appendTo(that.sessionsListElement);
                    that._runNextSessionsLoader();
                })
                .error(function(){
                    that._runNextSessionsLoader();
                })
        },
        destroy: function()
        {
            this.stopLooping = true;
            $.Widget.prototype.destroy.call(this);
        },
        _runNextSessionsLoader: function () {
            if (this.stopLooping) {
                return;
            }
            var that = this;
            setTimeout(function () {
                that._loadSessionInfo(false);
            }, that.options.updatefrequency);
        },

        _create:function(){
            this.sessionsListElement = $('<div class="sessionsList"/>');
            this.sessionsListElement.appendTo(this.element);

            this.chatPlaceholder = $('<div class="chatPlaceHolder"/>');
            this.chatPlaceholder.appendTo(this.element);

            this.tabs = $('<div class="subtabs"/>');
            this.tabs.appendTo(this.chatPlaceholder);

            this.emptyDiv = $('<div class="emptyTexDiv">' + this.options.emptyAreaText + '</div>');
            this.emptyDiv.appendTo(this.element);

            //this.tabs.html('<ul><li><a href="#tabs-1">Nunc tincidunt</a> <span class="ui-icon ui-icon-close" role="presentation">Remove Tab</span></li></ul><div id="tabs-1"><p>P</p></div>');
            this.tabs.html('<ul></ul>');

            this.tabs.tabs();
            this.tabs.children().addClass("filt");
            $('li', this.tabs).addClass("filt");

            $('<p>Список диалогов</p>').appendTo(this.sessionsListElement);

            var that = this;

            this.tabs.delegate("span.ui-icon-close", "click", function () {
                var panelId = $(this).closest("li").remove().attr("aria-controls");
                $('.widgetholder' + panelId, this.tabs).onlinechat('destroy');
                $("#" + panelId).remove();
                that.realTabCounter--;
                that.tabs.tabs("refresh");
                that._syncEmptyAreaDiv();
            });

            this._loadSessionInfo();
        }
    })
})(jQuery);